package com.banyou.banyou.main.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banyou.banyou.R;
import com.banyou.banyou.adapter.IllnessGridAdapter;
import com.banyou.banyou.base.BaseFragment;
import com.banyou.banyou.bean.main.setting.UserInfoBean;
import com.banyou.banyou.customviews.ScrollGridView;
import com.banyou.banyou.main.history.HistoryActivity;
import com.banyou.banyou.main.setting.SettingActivity;
import com.banyou.banyou.util.DialogFactory;
import com.banyou.banyou.util.FontDisplayUtil;
import com.banyou.banyou.util.GlideUtil;
import com.banyou.banyou.util.RxBus;
import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.webutils.ProgressSubscriber;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.OptionPicker;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import static com.banyou.banyou.util.Constants.REFRESH_LIST_FRAGMENT;
import static com.banyou.banyou.util.Constants.REFRESH_MY_FRAGMENT;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class MyFragment extends BaseFragment<MyPresenter> implements MyContract.View {

    @BindView(R.id.title_bar)
    RelativeLayout mTitleBar;
    @BindView(R.id.my_head)
    ImageView mMyHead;
    @BindView(R.id.my_setting)
    ImageView mMySetting;
    @BindView(R.id.my_name)
    TextView mMyName;
    @BindView(R.id.star_content)
    LinearLayout mStarContent;
    @BindView(R.id.setting_content)
    RelativeLayout mSettingContent;
    @BindView(R.id.sex)
    TextView mSex;
    @BindView(R.id.age)
    TextView mAge;
    @BindView(R.id.city)
    TextView mCity;
    @BindView(R.id.remark)
    TextView mRemark;
    @BindView(R.id.card_type)
    TextView mCardType;
    @BindView(R.id.card_no)
    TextView mCardNo;
    @BindView(R.id.accompanying_msg)
    LinearLayout mAccompanyingMsg;
    @BindView(R.id.photos)
    ScrollGridView mGridView;

    private UserViewHolder mUserHolder;
    private AccompontingViewHolder mAccompontingHolder;
    private AlertDialog mDialog, mPayTypeDialog;
    private EditText mMoneyEdit;
    private boolean isLazyLoaded;
    private String mUserType;
    private ViewHolder mHolder;
    private String mMoney;
    private String mPayType;
    private String mOutNo, mBankNo = "0";
    private List<String> mPhotoList = new ArrayList<>();
    private IllnessGridAdapter mAdapter;
    private Subscription mSubscribe;
    @Override
    protected void init() {
        mPresenter.initPresenter(this, new MyModel());
        mUserType = getSharedPreference().getString("userType", "2");
        if (mUserType.equals("1")) {
            initUserLayout();
        } else {
            initAccompontingLayout();
            mAdapter = new IllnessGridAdapter(mPhotoList, getActivity());
            mGridView.setAdapter(mAdapter);
        }
        initListener();
    }

    /**
     * 注册监听器
     */
    private void initListener() {
        //注册刷新RxBus
        mSubscribe = RxBus.getInstance().toObserverable().observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Object>() {
            @Override
            public void call(Object o) {
                if (o instanceof String) {
                    if (o.equals(REFRESH_MY_FRAGMENT)) {
                        mPresenter.getInfo(getSharedPreference().getString("userId",""));
                    }
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSubscribe.unsubscribe();
    }

    /**
     * 加载伴游
     */
    private void initAccompontingLayout() {
        mSettingContent.removeAllViews();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_my_accomponting, null);
        mAccompontingHolder = new AccompontingViewHolder(view);
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(p);
        mSettingContent.addView(view);
        mAccompontingHolder.mEarnBtn.setTextColor(getResources().getColor(R.color.text_deap_gray));
        mAccompontingHolder.mEarnBtn.setText("立即提款");
        mAccompontingHolder.mChooseBankBtn.setVisibility(View.GONE);
        mAccompontingHolder.mChoosePaytypeBtn.setVisibility(View.GONE);
        mAccompontingHolder.mGetMoneyBtn.setVisibility(View.GONE);
        mAccompontingHolder.mEditText.setVisibility(View.GONE);
        mAccompontingHolder.mEarnBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createDialog();
            }
        });
        //选择银行点击事件
        mAccompontingHolder.mChooseBankBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createChooseBankDialog();
            }
        });
        //选择付款方式点击事件
        mAccompontingHolder.mChoosePaytypeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createPayTypeDialog();
            }
        });
        //确定提款按钮点击事件
        mAccompontingHolder.mGetMoneyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAccompontingHolder.mEditText.getText().toString().trim().length() == 0) {
                    ShowToast.showToast("请输入您的提款账号");
                } else {
                    KLog.a("userid======>" + mMoney + ",kahao=" + mAccompontingHolder.mEditText.getText().toString() + ",mBankNo=" + mBankNo + ",mPayType=" + mPayType);
                    mPresenter.getMoney(getSharedPreference().getString("userId", getSharedPreference().getString("userId", "")), mMoney, mAccompontingHolder.mEditText.getText().toString(), mBankNo, mPayType);
                }

            }
        });
        //取款历史查询
        mAccompontingHolder.mHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HistoryActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 创建EditText输入dialog
     */
    private void createDialog() {
        DialogFactory factory = new DialogFactory(getActivity());
        factory.setCancleAble(true);
        mDialog = factory.createDialog("请输入取款金额");
        factory.setOneButton(true)
                .setSureBtnText("确定")
                .setOnBtnClickListener(new DialogFactory.OnBtnClickListener() {
                    @Override
                    public void onSureClick(View view) {
                        if (isNumeric(mMoneyEdit.getText().toString())) {
                            mMoney = mMoneyEdit.getText().toString();
                            mAccompontingHolder.mEarnBtn.setText("提款金额：" + mMoney + "￥");
                            mAccompontingHolder.mEarnBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mAccompontingHolder.mChoosePaytypeBtn.setVisibility(View.VISIBLE);
                            mAccompontingHolder.mGetMoneyBtn.setVisibility(View.VISIBLE);
                        } else {
                            ShowToast.showToast("请输入整数");
                        }
                        mDialog.dismiss();

                    }

                    @Override
                    public void onCancleClick(View view) {

                    }
                });
        mMoneyEdit = new EditText(getActivity());
        mMoneyEdit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        mMoneyEdit.setHint("请输入金额(必须是整数）");
        mMoneyEdit.setPadding(FontDisplayUtil.dip2px(10), 0, FontDisplayUtil.dip2px(10), 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, FontDisplayUtil.dip2px(40));
        params.setMargins(0, 0, 0, FontDisplayUtil.dip2px(10));
        mMoneyEdit.setLayoutParams(params);
        mMoneyEdit.setBackground(getResources().getDrawable(R.drawable.edit_text_background));
        factory.setView(mMoneyEdit);
        mDialog.show();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
            mPresenter.getInfo(getSharedPreference().getString("userId", ""));
    }

    /**
     * 加载游客
     */
    private void initUserLayout() {
        mAccompanyingMsg.setVisibility(View.GONE);
        mSettingContent.removeAllViews();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_my_user, null);
        mUserHolder = new UserViewHolder(view);
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(p);
        mSettingContent.addView(view);
        mUserHolder.mMoneyUsed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 跳转消费历史页面
            }
        });
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_my;
    }

    @Override
    protected MyPresenter initPresenter() {
        return new MyPresenter();
    }

    @OnClick({R.id.my_setting})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.my_setting:
                Intent intent = new Intent(getActivity(), SettingActivity.class);
                getActivity().startActivity(intent);
                break;
        }
    }

    /**
     * 创建Dialog
     */
    private void createChooseBankDialog() {
        //TODO 银行根据真实写
        String[] str = new String[4];
        str[0] = "哇啦银行";
        str[1] = "哇啦啦银行";
        str[2] = "哇啦啦啦银行";
        str[3] = "哇啦啦啦啦银行";
        OptionPicker picker = new OptionPicker(getActivity(), str);
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                mAccompontingHolder.mChooseBankBtn.setText(item);
                mAccompontingHolder.mChooseBankBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                mBankNo = item;
            }
        });
        picker.show();
    }

    /**
     * 创建一个支付选择dialog
     */
    private void createPayTypeDialog() {
        DialogFactory factory = new DialogFactory(getActivity());
        factory.setCancleAble(true);
        mPayTypeDialog = factory.createDialog("请输入取款金额");
        factory.setOneButton(true)
                .setSureBtnText("确定")
                .setOnBtnClickListener(new DialogFactory.OnBtnClickListener() {
                    @Override
                    public void onSureClick(View view) {
                        mPayTypeDialog.dismiss();
                        if (mHolder.mGroup.getCheckedRadioButtonId() == -1) {
                            ShowToast.showToast("请选择一种支付方式");
                        } else {
                            if (mHolder.mYinlianBtn.isChecked()) {
                                mAccompontingHolder.mChooseBankBtn.setVisibility(View.VISIBLE);
                            }
                            switch (mHolder.mGroup.getCheckedRadioButtonId()) {
                                case R.id.weixin_btn:
                                    mAccompontingHolder.mChoosePaytypeBtn.setText("付款方式：微信");
                                    mAccompontingHolder.mChooseBankBtn.setVisibility(View.GONE);
                                    mAccompontingHolder.mEditText.setHint("请输入微信号");
                                    mPayType = "3";
                                    break;
                                case R.id.zhifubao_btn:
                                    mAccompontingHolder.mChoosePaytypeBtn.setText("付款方式：支付宝");
                                    mAccompontingHolder.mChooseBankBtn.setVisibility(View.GONE);
                                    mAccompontingHolder.mEditText.setHint("请输入支付宝账号");
                                    mPayType = "4";
                                    break;
                                case R.id.yinlian_btn:
                                    mAccompontingHolder.mChoosePaytypeBtn.setText("付款方式：银联");
                                    mAccompontingHolder.mEditText.setHint("请输入银行卡号");
                                    mPayType = "1";
                                    break;
                            }
                            mAccompontingHolder.mChoosePaytypeBtn.setTextColor(getResources().getColor(R.color.orange_ff9933));
                            mAccompontingHolder.mEditText.setVisibility(View.VISIBLE);
                        }

                    }

                    @Override
                    public void onCancleClick(View view) {

                    }
                });
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_paytype, null);
        mHolder = new ViewHolder(view);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, FontDisplayUtil.dip2px(10));
        view.setLayoutParams(params);
        factory.setView(view);
        mPayTypeDialog.show();
    }

    /**
     * 取款成功
     */
    @Override
    public void getMoneySuccess() {
        ShowToast.showToast("取款成功");
        initAccompontingLayout();
    }

    /**
     * 取款失败
     */
    @Override
    public void getMoneyFail(Throwable e) {
        if (e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        } else {
            ShowToast.showToast("取款失败");
        }
    }


    static class UserViewHolder {
        @BindView(R.id.money_used)
        TextView mMoneyUsed;

        UserViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    static class AccompontingViewHolder {
        @BindView(R.id.money_earn)
        TextView mMoneyEarn;
        @BindView(R.id.money_daily)
        TextView mMoneyDaily;
        @BindView(R.id.earn_btn)
        Button mEarnBtn;
        @BindView(R.id.choose_paytype_btn)
        Button mChoosePaytypeBtn;
        @BindView(R.id.choose_bank_btn)
        Button mChooseBankBtn;
        @BindView(R.id.get_money_btn)
        Button mGetMoneyBtn;
        @BindView(R.id.edit_account)
        EditText mEditText;
        @BindView(R.id.history_btn)
        RelativeLayout mHistory;

        AccompontingViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    public static boolean isNumeric(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }


    /**
     * 获取信息成功
     *
     * @param bean
     */
    @Override
    public void getInfoSuccess(UserInfoBean bean) {
        GlideUtil.circleLoad(getActivity(), bean.getPORTAL_IMAG_PATH(), mMyHead);
        mMyName.setText(bean.getUserName());
        mStarContent.removeAllViews();
        for (int i = 0; i < bean.getLevel(); i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setLayoutParams(new LinearLayout.LayoutParams(FontDisplayUtil.dip2px(15), FontDisplayUtil.dip2px(15)));
            imageView.setImageResource(R.drawable.star);
            mStarContent.addView(imageView);
        }
        mBankNo = "0";
        if (getSharedPreference().getString("userType", "").equals("1")) {
            mUserHolder.mMoneyUsed.setText(bean.getConsumeBalance() + "￥");
        } else {
            mAccompontingHolder.mMoneyDaily.setText(bean.getReward() + "￥/天");
            mAccompontingHolder.mMoneyEarn.setText(bean.getBalance() + "￥");
            mPhotoList.clear();
            mPhotoList.addAll(bean.getUSER_PHOTO_ALUM());
            mAdapter.notifyDataSetChanged();
        }
        if (bean.getSex().equals('F')) {
            mSex.setText("性别：女");
        } else {
            mSex.setText("性别：男");
        }
        if (bean.getAGE() != null)
            mAge.setText("年龄：" + bean.getAGE());
        if (bean.getRegionName() != null)
            mCity.setText("城市：" + bean.getRegionName());
        if (bean.getRemarks() != null)
            mRemark.setText("个人介绍：" + bean.getRemarks());
        if (bean.getCertType() != null)
            switch (bean.getCertType()) {
                case "1":
                    mCardType.setText("证件类型：身份证");
                    break;
                case "2":
                    mCardType.setText("证件类型：护照");
                    break;
                case "3":
                    mCardType.setText("证件类型：军人证");
                    break;
            }
        if (bean.getCertNo() != null)
            mCardNo.setText("证件号：" + bean.getCertNo());
    }

    /**
     * 获取信息失败
     */
    @Override
    public void getInfoFail() {
        Toast.makeText(getActivity(), "获取信息失败", Toast.LENGTH_SHORT).show();
    }

    static class ViewHolder {
        @BindView(R.id.weixin_btn)
        RadioButton mWeixinBtn;
        @BindView(R.id.zhifubao_btn)
        RadioButton mZhifubaoBtn;
        @BindView(R.id.yinlian_btn)
        RadioButton mYinlianBtn;
        @BindView(R.id.paytype_group)
        RadioGroup mGroup;


        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
